<?php

namespace App\Http\Middleware;

use App\Models\Manage;
use Closure;
use Illuminate\Http\Request;

/**
 * 验证后台管理员token
 */
class CheckAdminToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
       
        $manage_token = $this->getToken($request);

        if(empty($manage_token)){
            return  response()->json(['code'=> 205,'msg' => 'token无效']);
        }

        //验证token有效期
        $manage_info = Manage::where('token' , $manage_token)->where('is_del' , 1)->first();
        if(empty($manage_info)){
            return  response()->json(['code'=> 205,'msg' => 'token无效']);
        }
        if($manage_info->expire_time < date('Y-m-d H:i:s')){
            return  response()->json(['code'=> 205,'msg' => '登录已过期，请重新登录']);
        }
        //刷新token过期时间
        $manage_info->expire_time = date("Y-m-d H:i:s",(time() + config('other.admin_token_refresh_time')));
        $manage_info->save();
        $request->manage_guid = $manage_info->guid;
        $request->manage_id = $manage_info->id;
        $request->manage_info = $manage_info;

        return $next($request);
    }

    /**
     * 获取请求参数中的 token 
     * @param request  object 请求参数对象
     */
    public function getToken($request){
        $authorization = $request->header('authorization');
        if(strpos($authorization , 'Bearer ') === false){
           // return null;//token格式不正确，不允许请求
            return request()->token;
        }

        return str_replace('Bearer ','',$request->header('authorization'));
    }


}
